from fastapi import FastAPI
import uvicorn
from fastapi import APIRouter, Depends
from fastapi import Depends, FastAPI, Header, HTTPException,Query
from myapi import myapi
from openapi import openapi
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import asyncio
import json
app = FastAPI()
async def verifyToken(x_token: str = Header()):
    """ token验证 """
    print("x_token:", x_token)
    if x_token is None:
        raise HTTPException(status_code=401, detail="X-Token header missing")
    # 在这里进行验证 token 的逻辑，这里简单地假设 token 为 "valid_token"
    if x_token != "112334455":
        raise HTTPException(status_code=403, detail="Invalid token")
    return x_token
#http://127.0.0.1:6060/ts/get?x_token=112334455
async def verifyToken2(x_token: str = Query()):
    """ token验证 """
    print("x_token:", x_token)
    if x_token is None:
        raise HTTPException(status_code=401, detail="X-Token header missing")
    # 在这里进行验证 token 的逻辑，这里简单地假设 token 为 "valid_token"
    if x_token != "112334455":
        raise HTTPException(status_code=403, detail="Invalid token")
    return x_token


async def generate_events(request:Request):
    try:
        i = 0
        while True:
            # 检查客户端是否断开连接
            if await request.is_disconnected():
                break
                
            # 生成数据
            data = {
                "count": i,
                "message": f"This is message {i}"
            }
            
            # 按照 SSE 格式发送 JSON 数据
            yield f"data: {json.dumps(data)}\n\n"
            
            i += 1
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print("Client disconnected")

@app.get("/events")
async def event_stream(request: Request):
    print("Client connected")
    return StreamingResponse(
        generate_events(request),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no"  # 禁用 Nginx 缓冲
        }
    )

#include_router()⽅法，⽤于将分发路由添加到app中，prefix参数为路由前缀，tags参数为标签
app.include_router(myapi, prefix="/my", tags=["私有"],dependencies=[Depends( verifyToken2)])
app.include_router(openapi, prefix="/open", tags=["公开"])

if __name__ == '__main__':
    # 生产环境可以使用[Uvicorn],上线环境用ASGI 服务器
    import uvicorn

    print(__name__)
    #uvicorn.run("main:app", host="127.0.0.1", port=6060, reload=True)
    uvicorn.run("main:app", host="0.0.0.0", port=6262, reload=True)

